import { reactive } from 'vue'
import {MyExcel,exportExcelType} from './MyExcel'
import MyHttp from './MyHttp'
import { IsNumber } from './TypeUtil'

export interface TableColumn{
  title: string, 
  key: string ,
  width?:string,
  nwidth?:Number
}
export interface TableCalcColumn{
  title: string, 
  key: string ,
  calc:Function,
  
}


export interface MySimpleExportOptions{
  qm:any, 
  url: string, 
  name:string,
  columns:Array<TableColumn>
  lx?:string
}

// exceljs相关方法
export class MySimpleExport {
   
  public async exportExcel(options: MySimpleExportOptions): Promise<void> {
    const { 
        qm, 
        url, 
        name, 
        columns,
        lx=""} = options;
    
    const dstqm = Object.assign({},qm, {page:1,pageSize:20000} );
     
    let data:any[]=[];
    if(lx=="page")
    {
        let r=await new MyHttp().page(url,dstqm,
        {  },
        columns
      ); 
       
        data=r.data.records;
    }
    else if (lx=="list"){
        let  r=await new MyHttp().list(url,dstqm,
          {  },
          columns
        ); 
          data=r.data;
    }
    else{
      let  r=await new MyHttp().post(url,dstqm,
        {  } 
      ); 
      let rowNo=0;
      let data=r.data;
      if( (r.data as any).records){
        data=(r.data as any).records;
      }
      data.forEach((element: any)=>{   
        element.rowNo=++rowNo;    
        columns.forEach(  col1  =>{
          let col=col1 as TableCalcColumn;
          if( col.calc&&typeof(col.calc)=="function"){
            col.calc(element);
          }
        })
      }) 
    }
    
    const tableData =  data  ; 

    let header = new Array<string>();
    let customHeader = new Array<string>();
    const mergeList=reactive([]);
    columns.forEach( (element:TableColumn) => {
        if(!!element.key){
          header.push(element.key);
          customHeader.push(element.title);
        }
        if(!element.nwidth){
          element.nwidth=25;
          if(element.width){
            var sw=element.width.replaceAll("px","");
            if(IsNumber(sw)){
              element.nwidth=parseInt(sw)/4;
            }
          }
        }
    });

    console.info(columns)

    const exportExcel = () => {
      const excel = new MyExcel();
      excel.exportExcel({
        name: name,
        title: '',
        data: tableData,
        header,
        customHeader,
        mergeList,
        columns 
      })
    } 
    exportExcel();
    
  }
}
  